<template>
  <div class="processing-batch-container">
    <!-- 搜索区域 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item>
          <el-input v-model="searchForm.productName" placeholder="请输入产品名称" style="width: 150px;" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="searchForm.processorName" placeholder="请输入加工方" style="width: 150px;" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="success" @click="handleAdd">新增</el-button>
          <el-button 
            type="primary" 
            :disabled="selectedRows.length === 0"
            @click="handleGenerateQRCodes">
            批量生成二维码
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <el-table 
      :data="tableData" 
      border 
      style="width: 100%" 
      v-loading="loading"
      :height="400"
      :row-style="{height:'60px'}"
      :cell-style="{padding:'0px'}"
      :header-row-style="{height:'50px'}"
      :header-cell-style="{padding:'0px'}"
      @selection-change="handleSelectionChange">
      <el-table-column 
        type="selection" 
        width="55"
        :selectable="row => row.status === 1">
      </el-table-column>
      <el-table-column prop="id" label="批次号" width="80" align="center"></el-table-column>
      <el-table-column prop="productName" label="产品名称" width="120" align="center"></el-table-column>
      <el-table-column prop="processorName" label="加工方" width="120" align="center"></el-table-column>
      <el-table-column prop="processingDate" label="加工日期" width="120" align="center"></el-table-column>
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 0 ? 'warning' : 'success'">
            {{ scope.row.status === 0 ? '进行中' : '已完成' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" align="center">
        <template slot-scope="scope">
          {{ formatDateTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间" min-width="180" align="center">
        <template slot-scope="scope">
          {{ formatDateTime(scope.row.updateTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-edit"
            circle
            class="operation-button"
            @click="handleEdit(scope.row)"
            title="编辑">
          </el-button>
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            circle
            class="operation-button"
            @click="handleDelete(scope.row)"
            title="删除">
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[5, 10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px" :close-on-click-modal="false">
      <el-form :model="form" :rules="rules" ref="form" label-width="120px" @submit.native.prevent>
        <el-form-item label="产品" prop="productId">
          <el-select 
            v-model="form.productId" 
            placeholder="请选择产品" 
            style="width: 100%"
          >
            <el-option
              v-for="product in productOptions"
              :key="product.id"
              :label="product.name"
              :value="product.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="加工方" prop="processorId">
          <el-select 
            v-model="form.processorId" 
            placeholder="请选择加工方" 
            style="width: 100%"
          >
            <el-option
              v-for="processor in processorOptions"
              :key="processor.id"
              :label="processor.name"
              :value="processor.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="加工日期" prop="processingDate">
          <el-date-picker
            v-model="form.processingDate"
            type="date"
            placeholder="选择加工日期"
            style="width: 100%">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="进行中" :value="0"></el-option>
            <el-option label="已完成" :value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import http from '@/http/http'
import moment from 'moment'
import QRCode from 'qrcode'
import JSZip from 'jszip'
import { saveAs } from 'file-saver'

export default {
  name: 'ProcessingBatch',
  data() {
    return {
      // 搜索表单
      searchForm: {
        productName: '',
        processorName: ''
      },
      // 表格数据
      tableData: [],
      loading: false,
      // 分页
      page: 1,
      pageSize: 5,
      total: 0,
      // 对话框
      dialogVisible: false,
      dialogTitle: '新增加工批次',
      // 产品选项
      productOptions: [],
      // 加工方选项
      processorOptions: [],
      // 表单
      form: {
        id: null,
        productId: '',
        processorId: '',
        batchId: '',
        processingDate: '',
        status: 0
      },
      // 表单验证规则
      rules: {
        productId: [
          { required: true, message: '请选择产品', trigger: ['change', 'blur'] }
        ],
        processorId: [
          { required: true, message: '请选择加工方', trigger: ['change', 'blur'] }
        ],
        batchId: [
          { required: true, message: '请输入批次号', trigger: 'blur' }
        ],
        processingDate: [
          { required: true, message: '请选择加工日期', trigger: ['change', 'blur'] }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: ['change', 'blur'] }
        ]
      },
      selectedRows: []
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    formatDateTime(time) {
      return time ? moment(time).format('YY-MM-DD HH:mm:ss') : '--'
    },
    // 获取数据
    async fetchData() {
      this.loading = true
      try {
        const params = {
          page: this.page,
          pageSize: this.pageSize
        }
        const res = await http.processingBatch.getList(params)
        if (res.data.code === 200) {
          this.tableData = res.data.data
          this.total = res.data.total
        }
      } catch (error) {
        console.error('获取数据失败:', error)
        this.$message.error('获取数据失败')
      } finally {
        this.loading = false
      }
    },

    // 获取产品列表
    async getProductList() {
      try {
        const res = await http.product.getName()
        if (res.data.code === 200) {
          this.productOptions = res.data.data.map(item => ({
            id: item.id,
            name: item.name
          }))
        }
      } catch (error) {
        console.error('获取产品列表失败:', error)
        this.$message.error('获取产品列表失败')
      }
    },

    // 获取加工方列表
    async getProcessorList() {
      try {
        const res = await http.processor.getName()
        if (res.data.code === 200) {
          this.processorOptions = res.data.data.map(item => ({
            id: item.id,
            name: item.name
          }))
        }
      } catch (error) {
        console.error('获取加工方列表失败:', error)
        this.$message.error('获取加工方列表失败')
      }
    },

    // 搜索
    async handleSearch() {
      this.page = 1
      this.loading = true
      try {
        const params = {
          page: this.page,
          pageSize: this.pageSize,
          productName: this.searchForm.productName || null,
          processorName: this.searchForm.processorName || null
        }
        const res = await http.processingBatch.getByCondition(params)
        if (res.data.code === 200) {
          this.tableData = res.data.data
          this.total = res.data.total
        }
      } catch (error) {
        console.error('搜索失败:', error)
        this.$message.error('搜索失败')
      } finally {
        this.loading = false
      }
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        productName: '',
        processorName: ''
      }
      this.page = 1
      this.fetchData()
    },

    // 新增
    handleAdd() {
      this.dialogTitle = '新增加工批次'
      // 获取产品和加工方列表
      this.getProductList()
      this.getProcessorList()
      this.form = {
        id: null,
        productId: '',
        processorId: '',
        batchId: '',
        processingDate: moment().format('YYYY-MM-DD'),
        status: 0
      }
      this.dialogVisible = true
    },

    // 编辑
    async handleEdit(row) {
      this.dialogTitle = '编辑加工批次'
      // 先获取产品和加工方列表
      await Promise.all([
        this.getProductList(),
        this.getProcessorList()
      ])
      
      // 设置表单数据
      this.form = {
        ...row,
        productId: row.productId,
        processorId: row.processorId
      }
      
      this.dialogVisible = true
    },

    // 删除
    handleDelete(row) {
      this.$confirm('确认删除该加工批次?', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          const res = await http.processingBatch.deleteBatch(row.id)
          if (res.data.code === 200) {
            this.$message.success('删除成功')
            this.fetchData()
          }
        } catch (error) {
          this.$message.error('删除失败')
        }
      }).catch(() => {})
    },

    // 提交表单
    submitForm() {
      console.log('点击提交按钮')
      this.$refs.form.validate(async (valid) => {
        console.log('表单验证结果:', valid)
        if (valid) {
          try {
            console.log('提交的表单数据:', this.form)
            const res = await http.processingBatch.save(this.form)
            console.log('提交响应:', res)
            if (res.data.code === 200) {
              this.$message.success(this.form.id ? '更新成功' : '添加成功')
              this.dialogVisible = false
              this.fetchData()
            } else {
              this.$message.error(res.data.msg || '操作失败')
            }
          } catch (error) {
            console.error('提交失败:', error)
            this.$message.error(this.form.id ? '更新失败' : '添加失败')
          }
        }
      })
    },

    // 分页相关方法
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.page = val
      this.fetchData()
    },

    // 处理表格选择变化
    handleSelectionChange(selection) {
      this.selectedRows = selection
    },

    // 生成并下载二维码
    async handleGenerateQRCodes() {
      try {
        this.loading = true
        const batchIds = this.selectedRows.map(row => row.id)
        
        // 调用后端接口获取加密数据
        const res = await http.processingBatch.generateQRCodesBatch(batchIds)
        
        if (res.data.code === 200) {
          const qrcodeDataList = res.data.data
          
          // 创建一个ZIP文件
          const zip = new JSZip()
          
          // 为每个加密数据生成二维码
          const qrcodePromises = qrcodeDataList.map(async (encryptedData, index) => {
            try {
              const qrcodeDataUrl = await QRCode.toDataURL(encryptedData, {
                errorCorrectionLevel: 'H',
                margin: 1,
                width: 400
              })
              
              // 将base64图片数据转换为二进制
              const imageData = qrcodeDataUrl.replace('data:image/png;base64,', '')
              const batchInfo = this.selectedRows[index]
              
              // 添加到ZIP文件，使用批次信息作为文件名
              zip.file(`${batchInfo.productName}_${batchInfo.id}.png`, imageData, {base64: true})
            } catch (error) {
              console.error('生成二维码失败:', error)
              throw error
            }
          })
          
          // 等待所有二维码生成完成
          await Promise.all(qrcodePromises)
          
          // 生成并下载ZIP文件
          const zipContent = await zip.generateAsync({type: 'blob'})
          saveAs(zipContent, `qrcodes_${moment().format('YYYYMMDD_HHmmss')}.zip`)
          
          this.$message.success('二维码生成成功')
        } else {
          this.$message.error(res.data.msg || '生成二维码失败')
        }
      } catch (error) {
        console.error('生成二维码失败:', error)
        this.$message.error('生成二维码失败')
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style scoped>
.processing-batch-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 100px);
}

.search-bar {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  align-items: center;
}

/* 重置输入框样式 */
.search-form .el-input__inner {
  background-color: #fff;
  border: 1px solid #dcdfe6;
  color: #606266;
  text-align: left;
}

.search-form .el-input__inner:hover {
  border-color: #c0c4cc;
}

.search-form .el-input__inner:focus {
  border-color: #409EFF;
}

.el-button + .el-button {
  margin-left: 12px;
}

.el-table {
  margin-top: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.pagination-container {
  text-align: right;
  margin-top: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

/* 操作按钮样式 */
.operation-button.el-button.is-circle {
  width: 36px;
  height: 36px;
  padding: 9px;
  transition: all 0.3s ease;
  margin: 0 8px;
}

.operation-button.el-button.is-circle [class^="el-icon-"] {
  font-size: 16px;
  line-height: 1;
  vertical-align: -1px;
}

.operation-button.el-button.is-circle:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

/* 编辑按钮特定样式 */
.operation-button.el-button--primary.is-circle {
  background: linear-gradient(135deg, #409EFF, #3a8ee6);
}

/* 删除按钮特定样式 */
.operation-button.el-button--danger.is-circle {
  background: linear-gradient(135deg, #f56c6c, #e74c3c);
}

/* 表单输入框左对齐 */
.el-form-item .el-input__inner,
.el-form-item .el-input-number__decrease,
.el-form-item .el-input-number__increase {
  text-align: left;
}

.el-form-item .el-input-number .el-input__inner {
  text-align: left;
  padding-left: 8px;
}

/* 设置表格行高 */
.processing-batch-container ::v-deep .el-table__row {
  height: 67px !important;
}

/* 设置表头行高 */
.processing-batch-container ::v-deep .el-table__header-row {
  height: 50px !important;
}

/* 设置单元格内边距和行高 */
.processing-batch-container ::v-deep .cell {
  padding: 0 !important;
  line-height: 69px;
}

/* 设置表头单元格行高 */
.processing-batch-container ::v-deep .el-table__header .cell {
  line-height: 50px;
}

/* 设置选择框样式 */
.processing-batch-container ::v-deep .el-table-column--selection .cell {
  padding: 0 14px !important;
  display: flex;
  align-items: center;
  justify-content: center;
}

.processing-batch-container ::v-deep .el-checkbox {
  margin-right: 0;
}

/* 其他Element组件样式前都添加 ::v-deep 和父级选择器 */
.processing-batch-container ::v-deep .el-button--primary.is-circle {
  background: linear-gradient(135deg, #409EFF, #3a8ee6);
}
</style>
